<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>俄罗斯方块</title>
    <style>
        body {
            background: #000;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
        }
        canvas {
            border: 2px solid #fff;
            background: #111;
        }
    </style>
</head>
<body>
<canvas id="tetris" width="300" height="600"></canvas>

<script>
    const canvas = document.getElementById('tetris');
    const context = canvas.getContext('2d');
    context.scale(30, 30); // 放大画布以便看清方块

    // 创建空白的游戏区域
    let arenaWidth = 10;
    let arenaHeight = 20;
    let arena = createMatrix(arenaWidth, arenaHeight);

    // 创建方块形状
    const pieces = 'TJLOSZI';

    // 创建不同形状的矩阵
    function createPiece(type) {
        let matrix;
        
        // 定义不同形状的矩阵
        switch (type) {
            case 'T':
                matrix = [
                    [0, 1, 0],
                    [1, 1, 1],
                    [0, 0, 0],
                ];
                break;
            case 'J':
                matrix = [
                    [1, 0, 0],
                    [1, 1, 1],
                    [0, 0, 0],
                ];
                break;
            case 'L':
                matrix = [
                    [0, 0, 1],
                    [1, 1, 1],
                    [0, 0, 0],
                ];
                break;
            case 'O':
                matrix = [
                    [1, 1],
                    [1, 1],
                ];
                break;
            case 'S':
                matrix = [
                    [0, 1, 1],
                    [1, 1, 0],
                    [0, 0, 0],
                ];
                break;
            case 'Z':
                matrix = [
                    [1, 1, 0],
                    [0, 1, 1],
                    [0, 0, 0],
                ];
                break;
            case 'I':
                matrix = [
                    [0, 0, 0, 0],
                    [1, 1, 1, 1],
                    [0, 0, 0, 0],
                    [0, 0, 0, 0],
                ];
                break;
            default:
                matrix = [];
                break;
        }
        
        // 为矩阵添加类型信息用于颜色绘制
        matrix.type = type;
        return matrix;
    }

    // 创建空白矩阵
    function createMatrix(w, h) {
        const matrix = [];
        while (h--) {
            matrix.push(new Array(w).fill(0));
        }
        return matrix;
    }

    // 绘制矩阵
    function drawMatrix(matrix, offset) {
        matrix.forEach((row, y) => {
            row.forEach((value, x) => {
                if (value !== 0) {
                    // 根据方块类型设置不同颜色
                    switch (matrix.type) {
                        case 'T': context.fillStyle = 'purple'; break;
                        case 'J': context.fillStyle = 'blue'; break;
                        case 'L': context.fillStyle = 'orange'; break;
                        case 'O': context.fillStyle = 'yellow'; break;
                        case 'S': context.fillStyle = 'green'; break;
                        case 'Z': context.fillStyle = 'red'; break;
                        case 'I': context.fillStyle = 'cyan'; break;
                        default: context.fillStyle = 'white'; break;
                    }
                    context.fillRect(x + offset.x, y + offset.y, 1, 1);
                }
            });
        });
    }

    // 合并方块到游戏区域
    function merge(arena, player) {
        player.matrix.forEach((row, y) => {
            row.forEach((value, x) => {
                if (value !== 0) {
                    arena[y + player.pos.y][x + player.pos.x] = value;
                }
            });
        });
    }

    // 碰撞检测
    function collide(arena, player) {
        const m = player.matrix;
        const o = player.pos;
        for (let y = 0; y < m.length; ++y) {
            for (let x = 0; x < m[y].length; ++x) {
                if (m[y][x] !== 0 && 
                   (arena[y + o.y] && arena[y + o.y] && 
                    arena[y + o.y][x + o.x]) !== 0) {
                    return true;
                }
            }
        }
        return false;
    }

    // 绘制游戏画面
    function draw() {
        context.fillStyle = '#111';
        context.fillRect(0, 0, canvas.width, canvas.height);

        drawMatrix(arena, {x: 0, y: 0});
        drawMatrix(player.matrix, player.pos);
    }

    // 方块下落
    function playerDrop() {
        player.pos.y++;
        if (collide(arena, player)) {
            player.pos.y--;
            merge(arena, player);
            playerReset();
            arenaSweep();
        }
        dropCounter = 0;
    }

    // 重置玩家方块
    function playerReset() {
        const piece = pieces[Math.floor(Math.random() * pieces.length)];
        player.matrix = createPiece(piece);
        player.pos.y = 0;
        player.pos.x = Math.floor(arenaWidth / 2) - 
                       Math.floor(player.matrix[0].length / 2);
        if (collide(arena, player)) {
            arena.forEach(row => row.fill(0)); // 游戏结束，清空游戏区域
        }
    }

    // 移动玩家方块
    function playerMove(dir) {
        player.pos.x += dir;
        if (collide(arena, player)) {
            player.pos.x -= dir;
        }
    }

    // 旋转方块
    function rotate(matrix) {
        const newMatrix = matrix.map((_, i) =>
            matrix.map(row => row[i])
        );
        return newMatrix.reverse();
    }

    function playerRotate() {
        const pos = player.pos.x;
        let offset = 1;
        player.matrix = rotate(player.matrix);
        while (collide(arena, player)) {
            player.pos.x += offset;
            offset = -(offset + (offset > 0 ? 1 : -1));
            if (offset > player.matrix[0].length) {
                rotate(player.matrix); // 恢复原状
                player.pos.x = pos;
                return;
            }
        }
    }

    // 扫描消除行
    function arenaSweep() {
        outer: for (let y = arena.length - 1; y >= 0; --y) {
            for (let x = 0; x < arena[y].length; ++x) {
                if (arena[y][x] === 0) {
                    continue outer;
                }
            }

            const row = arena.splice(y, 1)[0].fill(0);
            arena.unshift(row);
            ++y;
        }
    }

    // 更新游戏状态
    function update(time = 0) {
        const deltaTime = time - lastTime;
        lastTime = time;
        dropCounter += deltaTime;
        if (dropCounter > dropInterval) {
            playerDrop();
        }
        draw();
        requestAnimationFrame(update);
    }

    // 初始化游戏
    function init() {
        arena = createMatrix(arenaWidth, arenaHeight);
        playerReset();
        lastTime = performance.now();
        dropCounter = 0;
        update();
    }

    // 修改初始化游戏变量部分
    let dropCounter = 0;
    let dropInterval = 1000;
    let lastTime = performance.now();
    let player = {
        pos: {x: 0, y: 0},
        matrix: null,
    };
    
    // 修改后的碰撞检测函数
    function collide(arena, player) {
        const m = player.matrix;
        const o = player.pos;
        for (let y = 0; y < m.length; ++y) {
            for (let x = 0; x < m[y].length; ++x) {
                if (m[y][x] !== 0 && 
                   (arena[y + o.y] && arena[y + o.y] && 
                    arena[y + o.y][x + o.x]) !== 0) {
                    return true;
                }
            }
        }
        return false;
    }

    // 添加硬下降函数（之前遗漏了）
    function playerHardDrop() {
        while (player.pos.y < arenaHeight) {
            player.pos.y++;
            if (collide(arena, player)) {
                player.pos.y--;
                merge(arena, player);
                playerReset();
                arenaSweep();
                break;
            }
        }
        dropCounter = 0;
    }

    // 添加新的键盘控制逻辑
    document.addEventListener('keydown', event => {
        if (event.key === 'ArrowLeft') {
            playerMove(-1);
        } else if (event.key === 'ArrowRight') {
            playerMove(1);
        } else if (event.key === 'ArrowDown') {
            playerDrop();
        } else if (event.key === 'q' || event.key === 'Q') {
            playerRotate();
        } else if (event.key === ' ') { // 空格键用于旋转
            playerRotate();
        } else if (event.key === 'Shift') { // 使用Shift键进行硬下降
            playerHardDrop();
        }
    });

    // 开始新游戏
    init();
</script>
</body>
</html>